After creating the Alphabet, we are create the full words that represents the ECG


In [1]:
import psycopg2
from psycopg2.extensions import register_adapter, AsIs
from collections import Counter
import pandas as pd
import numpy as np
from time import time
from sklearn.decomposition import NMF, LatentDirichletAllocation
from sklearn.linear_model import LogisticRegression
np.set_printoptions(suppress=True,precision=10)

In [2]:
def obtainSubjects(dbname="mimic") :
    conn = psycopg2.connect("dbname="+dbname)
    cur = conn.cursor()
    select_stament = ("SELECT DISTINCT subject_id "
                      " FROM waveformqrst WHERE centroid IS NOT NULL" # limit 150"
    )
    cur.execute(select_stament)
    subject = []
    for row in cur :
        subject.append(row[0])
    conn.close()
    return subject

In [3]:
def obtainWord(subject,dbname="mimic") :
    conn = psycopg2.connect("dbname="+dbname)
    cur = conn.cursor()
    select_stament = ("SELECT centroid "
                      " FROM waveformqrst WHERE subject_id="+str(subject)+" ORDER BY qrtsorder"
    )
    cur.execute(select_stament)
    centroids = ""
    for row in cur :
        centroid = row[0]
        if centroid is not None :
            centroids= centroids+centroid
    conn.close()
    return centroids

In [4]:
def deleteWord(dbname="mimic") :
    conn = psycopg2.connect("dbname="+dbname)
    cur = conn.cursor()
    select_stament = "DELETE FROM subjectwords"
    cur.execute(select_stament)
    conn.commit()
    cur.close()
    conn.close()

In [5]:
def instertWord(words,dbname="mimic") :
    conn = psycopg2.connect("dbname="+dbname)
    cur = conn.cursor()
    insert_statement = 'INSERT into subjectwords (%s) values %s'
    columns = words.keys()
    values = [words[column] for column in columns]
#    print(cur.mogrify(insert_statement, (AsIs(','.join(columns)), tuple(values))))
    cur.execute(insert_statement, (AsIs(','.join(columns)), tuple(values)))
    conn.commit()
    cur.close()
    conn.close()

In [6]:
def selectWord(dbname="mimic") :
    conn = psycopg2.connect("dbname="+dbname)
    cur = conn.cursor()
    select_stament = ("SELECT subject_id,word "
                      " FROM subjectwords WHERE length(word)>1000"
    )
    cur.execute(select_stament)
    select = []
    for row in cur :
        select.append([row[0],row[1]])
    conn.close()
    return select

In [7]:
deleteWord()
subjects = obtainSubjects() 
print(len(subjects))
for subject in subjects :
    word = obtainWord(subject)
    if word is not None:
        words = {'subject_id':subject,'word':word}
        print(len(word),end=":")
        instertWord(words)
        print(words['subject_id'],end=",")


351
17462:16639,2831:3623,1990:7153,83:8985,12638:9070,1429:6901,11223:7009,20094:7442,17529:7492,134:12217,13364:571,8195:9732,14274:7612,13719:6673,3173:10487,2295:6889,5426:8814,12602:2990,16649:8698,18211:5933,14819:8533,8251:10656,13785:10738,482:7521,8815:10510,10302:3612,4699:8573,9361:2442,21441:8347,12006:1908,11411:11931,6602:7452,2386:3554,19583:4059,1230:7360,19392:4317,17462:6981,14628:20,18626:2148,13639:4068,18467:10595,18459:8198,7207:10209,15536:3745,3939:7522,19556:9425,17057:5336,6502:16172,49:8996,10885:3622,662:7981,6874:9335,18942:8415,23:90495,1050:1802,6:7517,16296:2185,9637:10534,60:2228,15759:10766,11356:8009,4369:8936,10755:8087,3:16909,47:12251,11622:12215,8856:9871,14725:10096,9265:8670,20418:7651,19588:9354,6178:9672,4495:6708,16253:9705,13058:10186,7259:5766,9133:7084,8302:7528,15301:7172,18272:135,4149:16709,7284:9630,1518:7799,5762:4865,13940:7685,14465:7289,18252:7860,10228:16360,20258:9366,13843:4180,9656:8336,833:11951,2506:3863,15075:4656,9632:10013,11113:9398,20579:974,18481:1222,22309:8451,13172:7786,20627:1004,4802:8734,17957:2492,2165:8084,8809:8870,15506:16607,15763:8524,20889:16490,12628:9005,9354:7048,14825:6607,18510:3798,2916:33,14115:1075,11154:7782,17762:5607,13215:4587,5363:16192,10176:9434,18381:4688,14667:16122,3556:1744,2054:9958,10162:7644,517:28065,14075:7371,2189:7448,4171:9949,90:7567,10471:3372,13055:7542,9325:408,20587:2049,12924:7225,10154:2917,10659:8569,3451:8121,2702:9363,9826:1569,11117:16280,12444:10077,12242:8654,15495:8207,
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-7-58db24183628> in <module>()
      3 print(len(subjects))
      4 for subject in subjects :
----> 5     word = obtainWord(subject)
      6     if word is not None:
      7         words = {'subject_id':subject,'word':word}

<ipython-input-3-cbef857e1121> in obtainWord(subject, dbname)
      5                       " FROM waveformqrst WHERE subject_id="+str(subject)+" ORDER BY qrtsorder"
      6     )
----> 7     cur.execute(select_stament)
      8     centroids = ""
      9     for row in cur :

/usr/lib/python3.4/encodings/utf_8.py in decode(input, errors)
     13 encode = codecs.utf_8_encode
     14 
---> 15 def decode(input, errors='strict'):
     16     return codecs.utf_8_decode(input, errors, True)
     17 

KeyboardInterrupt: 

In [ ]:
def get_all_substrings(input_string,length=5):
    substrings = []
    for j in range(len(input_string)) :
        for i in range(length) :
            substrings.append(input_string[j:j+i+1])
    return Counter(substrings)

In [ ]:
def existMatrix(word,subject,dbname="mimic") :
    conn = psycopg2.connect("dbname="+dbname)
    cur = conn.cursor()
    select_stament = ("SELECT 1 "
                      " FROM matrix WHERE subject_id='"+str(subject)+"' AND word='"+str(word)+"'"
    )
    cur.execute(select_stament)
    exist = False
    for row in cur :
        exist = True
    cur.close()
    conn.close()
    return exist

In [ ]:
def saveMatrix(matrix,dbname="mimic") :
    conn = psycopg2.connect("dbname="+dbname)
    cur = conn.cursor()
    insert_statement=('INSERT INTO matrix(word,subject_id,counting)'
                      ' SELECT unnest( %(word)s ) ,'
                      ' unnest( %(subject_id)s) ,'
                      ' unnest( %(counting)s)')
    word=[r['word'] for r in matrix]
    subject_id=[r['subject_id'] for r in matrix]
    counting=[r['counting'] for r in matrix]
#    print(cur.mogrify(insert_statement,locals()))
    cur.execute(insert_statement,locals())
    conn.commit()
    cur.close()
    conn.close()

In [ ]:
def cleanMatrix(dbname="mimic") :
    conn = psycopg2.connect("dbname="+dbname)
    cur = conn.cursor()
    select_stament = ("DELETE "
                      " FROM matrix"
    )
    cur.execute(select_stament)
    conn.commit()
    cur.close()
    conn.close()

In [ ]:
words = selectWord()
cleanMatrix()
i=0
for word in words :
    subject = word[0]
    subs =get_all_substrings(word[1],length=10)
    matrix = []
    for key in subs:
        matrix.append({'word':key,'counting':subs[key],'subject_id':subject})
#        if not existMatrix(key,subject) :
    if matrix != [] :
        print(i,end=",")
        i=i+1
        saveMatrix(matrix)
#    print(subs.keys())

In [ ]:
def selectMatrix(dbname="mimic") :
    conn = psycopg2.connect("dbname="+dbname)
    cur = conn.cursor()
    select_stament = ("SELECT subject_id,word,counting "
                      " FROM matrix ORDER BY subject_id"
    )
    cur.execute(select_stament)
    select = []
    for row in cur :
        select.append((row))
    cur.close()
    conn.close()
    return select

In [ ]:
labels = ['subject_id', 'Word', 'Counting']
df = pd.DataFrame.from_records(selectMatrix(), columns=labels)
table = pd.pivot_table(df,index=["subject_id"],columns=["Word"],values=["Counting"],
                       aggfunc={"Counting":[np.sum]},fill_value=0)
print(table)

In [ ]:
# Fit the NMF model
t0 = time()
nmf = NMF(n_components=30, random_state=1,alpha=.1, l1_ratio=.5)
W = nmf.fit_transform(table)
H = nmf.components_
print(W)
print("done in %0.3fs." % (time() - t0))

In [ ]:
print(np.shape(W))
print(np.shape(H))

In [ ]:
def patientIsAlive(patient,dbname="mimic") :
    conn = psycopg2.connect("dbname="+dbname)
    cur = conn.cursor()
    select_stament = ("SELECT dod "
                      " FROM patients WHERE subject_id = "+str(patient)
    )
    cur.execute(select_stament)
    select = []
    for row in cur :
        select.append(1 if row[0] is not None else 0 )
    cur.close()
    conn.close()
    return select

In [ ]:
patients = []
for patient in table.index :
    patients.append(patientIsAlive(patient)[0])
print(len(patients))

In [ ]:
# flatten y into a 1-D array
y = np.ravel(patients)
modelo_lr = LogisticRegression()
modelo_lr.fit(y=y,X=W)

In [ ]:
modelo_lr.score(W, y)

In [ ]:
y.mean()

In [ ]:
predicion = modelo_lr.predict(W[:1])
print(W[:1])
print(predicion,y[:1])

In [ ]:
modelo_lr

In [ ]: